<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">主页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col :span="8">
          <el-button type="primary" @click="getCate">添加分类</el-button>
        </el-col>
      </el-row>
      <tree-table class="treeTable" :data="categoriesList" border :expand-type="false" :selection-type="false" :columns="columns" show-index index-text="#" :show-row-hover="false">
        <template slot="isOk" slot-scope="scope">
          <i class="el-icon-success success" v-if="scope.row.cat_deleted === false"></i>
          <i class="el-icon-error error" v-else></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1" style="margin-left: 40px;">二级</el-tag>
          <el-tag type="warning" v-else-if="scope.row.cat_level === 2" style="margin-left: 80px;">三级</el-tag>
        </template>
        <template slot="operation" slot-scope="scope">
          <el-button size="mini" type="primary" class="el-icon-edit" @click="getThisCate(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" class="el-icon-delete" @click="deleteCate(scope.row)">删除</el-button>
        </template>
      </tree-table>
      <el-pagination @size-change="getCurrentSizeData" @current-change="getCurrentPageData" :current-page="queryParams.pagenum" :page-sizes="[3, 5, 8, 12]" :page-size="queryParams.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </el-card>
    <el-dialog title="添加分类" width="50%" :visible.sync="isAddGoodsDialogVisible" @close="resetFormData('add')" :close-on-click-modal="false">
      <el-form :model="addCateForm" ref="addCateFormRef" :rules="addCateFormRules" label-width="100px">
        <el-form-item label="分类名称:" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader @change="getCateKeys" ref="cascaderRef" :options="cateData" :props="cateProps" v-model="cateKeys" clearable></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddGoodsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addCate">确认</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改分类名称" :visible.sync="isEditDialogVisible" @close="resetFormData('edit')" :close-on-click-modal="false" width="50%">
      <el-form :model="editForm" ref="editCateFormRef" label-width="80px">
        <el-form-item label="分类名称">
          <el-input v-model="editForm.cat_name" v-focus></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editCate">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      queryParams: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      categoriesList: [],
      total: 0,
      columns: [{
        label: '分类名称',
        prop: 'cat_name'
      }, {
        label: '是否有效',
        type: 'template',
        template: 'isOk'
      }, {
        label: '排序',
        type: 'template',
        template: 'order'
      }, {
        label: '操作',
        type: 'template',
        template: 'operation'
      }],
      isAddGoodsDialogVisible: false,
      addCateForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      cateData: [],
      cateKeys: [],
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true
      },
      isEditDialogVisible: false,
      editForm: {
        cat_id: '',
        cat_name: ''
      }
    }
  },
  methods: {
    async getCategoriesList() {
      const { data: response } = await this.$http.get('categories', { params: this.queryParams })
      if(response.meta.status !== 200) return this.$message({ type: 'error', message: '获取分类列表失败', duration: 2000 })
      this.categoriesList = response.data.result
      this.total = response.data.total
    },
    getCurrentSizeData(newSize) {
      this.queryParams.pagesize = newSize
      this.getCategoriesList()
    },
    getCurrentPageData(newPage) {
      this.queryParams.pagenum = newPage
      this.getCategoriesList()
    },
    async getCate() {
      this.isAddGoodsDialogVisible = true
      const { data: response } = await this.$http.get('categories', { params: { type: 2 } })
      if(response.meta.status !== 200) return this.$message({ type: 'error', message: '获取分类数据失败！', duration: 2000 })
      this.cateData = response.data
    },
    getCateKeys() {
      this.addCateForm.cat_pid = this.cateKeys[this.cateKeys.length - 1]
      this.addCateForm.cat_level = this.cateKeys.length
    },
    resetFormData(val) {
      if(val === 'add') {
        this.$refs.addCateFormRef.resetFields()
      }else if(val === 'edit') {
        this.$refs.editCateFormRef.resetFields()
      }
      this.cateKeys = []
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_pid = 0
    },
    async addCate() {
      this.$refs.addCateFormRef.validate(async valid => {
        if(!valid) return
        const { data: response } = await this.$http.post('categories', this.addCateForm)
        if(response.meta.status !== 201) return this.$message({ type: 'error', message: '添加分类失败', duration: 2000 })
        this.$message({ type: 'success', message: '添加分类成功', duration: 2000 })
        this.getCategoriesList()
        this.isAddGoodsDialogVisible = false
      })
    },
    async getThisCate(info) {
      this.isEditDialogVisible = true
      const { data: response } = await this.$http.get('categories/' + info.cat_id)
      if(response.meta.status !== 200) return this.$message({ type: 'error', message: '获取分类数据失败', duration: 2000 })
      this.editForm.cat_name = response.data.cat_name
      this.editForm.cat_id = response.data.cat_id
    },
    async editCate() {
      const { data: response } = await this.$http.put('categories/' + this.editForm.cat_id, { cat_name: this.editForm.cat_name })
      if(response.meta.status !== 200) return this.$message({ type: 'error', message: '修改分类失败', duration: 2000 })
      this.$message({ type: 'success', message: '修改分类成功', duration: 2000 })
      this.getCategoriesList()
      this.isEditDialogVisible = false
    },
    async deleteCate(info) {
      if(this.total % this.queryParams.pagesize === 1) {
        this.queryParams.pagenum--
      }
      const flag = await this.$confirm('确定删除该权限吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if(flag !== 'confirm') return this.$message({ type: 'info', message: '已取消删除分类操作', duration: 2000 })
      const { data: response } = await this.$http.delete('categories/' + info.cat_id)
      if(response.meta.status !== 200) return console.log(response)
      this.$message({ type: 'success', message: '删除分类成功', duration: 2000 })
      this.getCategoriesList()
    }
  },
  watch: {
    cateKeys: function(val) {
      if(val !== '' && this.$refs.cascaderRef !== undefined) {
        this.$refs.cascaderRef.dropDownVisible = false
      }
    }
  },
  directives: {
    focus: {
      inserted: function(el) {
        el.focus()
      }
    }
  },
  created() {
    this.getCategoriesList()
  }
}
</script>

<style lang="less" scoped>
  .success {
    color: dodgerblue;
  }
  .error {
    color: red;
  }
  .treeTable{
    margin-top: 15px;
  }
  .el-cascader{
    width: 100%;
  }
</style>
